﻿using Microsoft.Extensions.DependencyInjection;
using System;
using Cms.Core.Infrastructure.Extension;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.AspNetCore.Mvc;

namespace Cms.Core.DynamicWebApi
{
    /// <summary>
    /// 添加动态API服务扩展
    /// </summary>
   public static class DynamicWebApiServiceExtensions
    {

        /// <summary>
        ///将动态WebAPI添加到容器
        /// </summary>
        /// <param name="services">服务</param>
        /// <param name="options">配置</param>
        /// <returns></returns>
        public static IServiceCollection AddDynamicWebApi(this IServiceCollection services, DynamicWebApiOptions options)
        {

            options.NotNull(nameof(options));
            options.Valid();

            AppConsts.DefaultAreaName = options.DefaultAreaName;
            AppConsts.DefaultHttpVerb = options.DefaultHttpVerb;
            AppConsts.DefaultApiPreFix = options.DefaultApiPrefix;
            AppConsts.ControllerPostfixes = options.RemoveControllerPostfixes;
            AppConsts.ActionPostfixes = options.RemoveActionPostfixes;
            AppConsts.FormBodyBindingIgnoredTypes = options.FormBodyBindingIgnoredTypes;

            var partManager = services.GetSingletonInstanceOrNull<ApplicationPartManager>();

            if (partManager == null)
            {
                throw new InvalidOperationException("\"AddDynamicWebApi\" must be after \"AddMvc\".");
            }

            // 添加自定义控制器检查器
            partManager.FeatureProviders.Add(new DynamicWebApiControllerFeatureProvider());

            services.Configure<MvcOptions>(o =>
            {
                // 寄存器控制器路由信息转换器
                o.Conventions.Add(new DynamicWebApiConvention(services));
            });

            return services;
        }

        public static IServiceCollection AddDynamicWebApi(this IServiceCollection services)
        {
            return AddDynamicWebApi(services, new DynamicWebApiOptions());
        }
    }
}
